#!/usr/bin/env python3
"""
系统资源监控和告警API
提供系统资源监控和告警的Web API接口
"""

import os
import json
from flask import Blueprint, jsonify, request

app = Blueprint('monitor', __name__)

@app.route('/system', methods=['GET'])
def get_system_metrics():
    """获取系统资源使用情况"""
    from web_service import resource_monitor
    metrics = resource_monitor.get_system_metrics()
    if metrics is None:
        return jsonify({'error': '获取系统指标失败'}), 500
    return jsonify(metrics)

@app.route('/process/<int:pid>', methods=['GET'])
def get_process_metrics(pid):
    """获取指定进程的资源使用情况"""
    from web_service import resource_monitor
    metrics = resource_monitor.get_process_metrics(pid)
    if metrics is None:
        return jsonify({'error': f'获取进程 {pid} 指标失败'}), 500
    return jsonify(metrics)

@app.route('/check', methods=['GET'])
def check_resources():
    """检查系统资源使用情况并触发告警"""
    from web_service import resource_monitor, alert_manager
    result = resource_monitor.check_resource_usage()
    if result['status'] != 'normal':
        alert_manager.process_alert(result)
    return jsonify(result)

@app.route('/alerts/history', methods=['GET'])
def get_alert_history():
    """获取告警历史记录"""
    limit = request.args.get('limit', default=10, type=int)
    from web_service import alert_manager
    history = alert_manager.get_alert_history(limit)
    return jsonify(history)

@app.route('/config', methods=['GET', 'POST'])
def manage_monitor_config():
    """管理监控配置"""
    if request.method == 'GET':
        from web_service import resource_monitor
        return jsonify({
            'warning_thresholds': resource_monitor.warning_thresholds,
            'critical_thresholds': resource_monitor.critical_thresholds
        })
    
    if request.method == 'POST':
        try:
            config = request.get_json()
            from web_service import resource_monitor
            if 'warning_thresholds' in config:
                resource_monitor.warning_thresholds.update(config['warning_thresholds'])
            if 'critical_thresholds' in config:
                resource_monitor.critical_thresholds.update(config['critical_thresholds'])
            return jsonify({'message': '监控配置更新成功'})
        except Exception as e:
            return jsonify({'error': f'更新监控配置失败: {str(e)}'}), 400

@app.route('/alerts/config', methods=['GET', 'POST'])
def manage_alert_config():
    """管理告警配置"""
    if request.method == 'GET':
        from web_service import alert_manager
        return jsonify(alert_manager.config)
    
    if request.method == 'POST':
        try:
            from web_service import alert_manager
            config = request.get_json()
            alert_manager.config.update(config)
            
            # 保存配置到文件
            config_path = os.path.join('config', 'alert_config.json')
            with open(config_path, 'w', encoding='utf-8') as f:
                json.dump(alert_manager.config, f, indent=4, ensure_ascii=False)
            
            return jsonify({'message': '告警配置更新成功'})
        except Exception as e:
            return jsonify({'error': f'更新告警配置失败: {str(e)}'}), 400